﻿using FaceRecognition.Model;
using OpenCvSharp;
using OpenCvSharp.Face;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FaceRecognition
{
    public partial class FrmUserInfo : Form
    {
        private Redis_DAL.GetData mGetData = null;
        private Redis_DAL.SetData mSetData = null;
        private List<Model.ImageInfo> mAllUsers = null;

        private FisherFaceRecognizer faceRecognizer;

        private delegate void AsyncAction();

        public FrmUserInfo()
        {
            InitializeComponent();
            mGetData = new Redis_DAL.GetData();
            mSetData = new Redis_DAL.SetData();
        }


        /// <summary>
        /// 窗体加载时清空显示内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmUserInfo_Load(object sender, EventArgs e)
        {
            this.label4.Text = "";
            this.label6.Text = "";
            this.label5.Text = "";
        }


        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            reloadData();
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        private void reloadData()
        {
            try
            {
                ClearControl();
                this.toolStripLabel1.Text = "正在刷新数据...";
                this.toolStripLabel1.Visible = true;
                this.toolStripLabel1.ForeColor = Color.Green;

                this.dataGridView1.Rows.Clear();
                List<Model.ImageInfo> list = this.mGetData.GetList<Model.ImageInfo>("Users");
                this.mAllUsers = new List<Model.ImageInfo>();
                foreach (var item in list)
                {
                    Model.ImageInfo info = new Model.ImageInfo();
                    info.ImageID = item.ImageID;
                    info.ImageGroupID = item.ImageGroupID;
                    info.Name = item.Name;
                    info.Gender = item.Gender;
                    info.HeadImage = item.HeadImage;
                    info.Image = new Mat(Application.StartupPath + info.HeadImage, ImreadModes.Grayscale);
                    this.mAllUsers.Add(info);
                }
                if (list == null || list.Count < 1)
                    return;

                foreach (Model.ImageInfo item in list)
                {
                    this.dataGridView1.Rows.Add(item.ImageID, item.Name, item.Gender, item.HeadImage);
                }

                this.dataGridView1.Sort(FID, ListSortDirection.Ascending);

                this.toolStripLabel1.Visible = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                this.toolStripLabel1.Text = "数据获取异常...";
                this.toolStripLabel1.Visible = true;
                this.toolStripLabel1.ForeColor = Color.Red;
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            FrmFaceInput input = new FrmFaceInput();
            input.ShowDialog();
            reloadData();
        }

        /// <summary>
        /// 训练机器识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// 开始人脸识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            try
            {
                if(this.dataGridView1.Rows.Count <= 1)
                {
                    MessageBox.Show("识别人数必须大于一人以上");
                    return;
                }

                List<Mat> mats = new List<Mat>();
                List<int> labs = new List<int>();
                for (int i = 0; i < this.mAllUsers.Count; i++)
                {
                    mats.Add(this.mAllUsers[i].Image);
                    labs.Add(this.mAllUsers[i].ImageGroupID);
                }
                faceRecognizer = FisherFaceRecognizer.Create();
                faceRecognizer.Train(mats, labs);
                //MessageBox.Show("训练完成");

                Console.WriteLine("机器识别完成");
                FrmRecognition reco = new FrmRecognition(this.mAllUsers, this.faceRecognizer);
                reco.Show();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
        }

        /// <summary>
        /// 单击查看信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.dataGridView1.Rows.Count < 1 || this.dataGridView1.SelectedRows.Count < 1)
                return;

            DataGridViewRow dr = this.dataGridView1.SelectedRows[0];
            this.label4.Text = dr.Cells[this.FID.Index].Value.ToString();
            this.label6.Text = dr.Cells[this.FName.Index].Value.ToString();
            this.label5.Text = dr.Cells[this.FGender.Index].Value.ToString();

            string imagePath = Application.StartupPath + dr.Cells[this.FPicPath.Index].Value.ToString();
            if (System.IO.File.Exists(imagePath))
            {
                //以流的形式显示图片，不然作删除时会占用文件
                using(FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    if (fs.Length <= 0)
                        return;
                    Image img = Image.FromStream(fs);
                    Bitmap map = (Bitmap)img.Clone();
                    img.Dispose();
                    this.pictureBox1.Image = map;
                }
             
            }
        }

        /// <summary>
        /// 清空控件内容
        /// </summary>
        private void ClearControl()
        {
            this.pictureBox1.Image = null;
            this.label4.Text = "";
            this.label6.Text = "";
            this.label5.Text = "";
        }

        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.Rows.Count < 1 || this.dataGridView1.SelectedRows.Count < 1)
                    return;

                DataGridViewRow dr = this.dataGridView1.SelectedRows[0];
                int id = Convert.ToInt32(dr.Cells[this.FID.Index].Value);

                ImageInfo mi = this.mAllUsers.Where(w => w.ImageID == id).ToList().FirstOrDefault();
                if (mi == null)
                    return;
                FrmFaceInput input = new FrmFaceInput(mi);
                input.ShowDialog();
                reloadData();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 删除个人信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.Rows.Count < 1 || this.dataGridView1.SelectedRows.Count < 1)
                    return;

                DataGridViewRow dr = this.dataGridView1.SelectedRows[0];
                int id = Convert.ToInt32(dr.Cells[this.FID.Index].Value);

                ImageInfo mi = this.mAllUsers.Where(w => w.ImageID == id).ToList().FirstOrDefault();
                if (mi == null)
                    return;
                mi.Image = null;
                bool flag = this.mSetData.DeleteList<ImageInfo>("Users", mi);

                string count = this.mGetData.GetKey<string>("FaceCount");
                int newCount = Convert.ToInt32(count) - 1;
                flag = this.mSetData.AddKey("FaceCount", newCount);
                if (flag)
                {
                    ClearControl();
                    string imgPath = Application.StartupPath + mi.HeadImage;
                    if (File.Exists(imgPath))
                        File.Delete(imgPath);
                    this.mAllUsers.Remove(mi);
                    this.dataGridView1.Rows.Remove(this.dataGridView1.SelectedRows[0]);
                    MessageBox.Show("已删除！");
                    reloadData();
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
        }
    }
}
